package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Commodity;
import cn.wolfcode.trip.base.domain.Sign;
import cn.wolfcode.trip.base.domain.Stock;
import cn.wolfcode.trip.base.service.ICommodityService;
import cn.wolfcode.trip.base.service.ISignService;
import cn.wolfcode.trip.base.service.IStockService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("buyCommodity")
public class BuyCommodityController {
    @Autowired
    private ICommodityService commodityService; //得到商品的价格
    @Autowired
    private ISignService signService; //得到用户的积分点数
    @Autowired
    private IStockService stockService; //得到商品的库存数量

    @PutMapping
    public JSONResult buyCommidity(Long commodityId){
        //得到商品的价格
        Commodity commodity = commodityService.selectByCommodityId(commodityId);
        int price = commodity.getPrice().intValue();
        //得到当前用户积分
        Sign sign = signService.getPointByUserId();
        //得到商品库存数量
        Stock stock = stockService.selectStockNumber(commodityId);
        if(stock.getNumber()<1){
            return new JSONResult().mark("商品库存不足");
        }else if(sign.getPoints() < price){
            return new JSONResult().mark("积分不足");
        }
        //减少用户积分
        sign.setPoints(sign.getPoints() - price);
        //减少库存数量
        stock.setNumber(stock.getNumber()-1);
        //更新用户积分
        signService.updatePoints(sign);
        //更新库存数量
        stockService.updateNumber(stock);
        return new JSONResult();
    }

}
